package com.ruoyi.web.controller.interview;

import java.io.*;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.HuaWeiSISUtils;
import com.ruoyi.common.utils.QiNiuUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.interview.domain.InterviewAnswer;
import com.ruoyi.interview.service.IInterviewAnswerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 面试回答Controller
 * 
 * @author z5
 * @date 2025-06-19
 */
@RestController
@RequestMapping("/interview/answer")
public class InterviewAnswerController extends BaseController
{
    @Autowired
    private IInterviewAnswerService interviewAnswerService;

    /**
     * 查询面试回答列表
     */
    @PreAuthorize("@ss.hasPermi('interview:answer:list')")
    @GetMapping("/list")
    public TableDataInfo list(InterviewAnswer interviewAnswer)
    {
        startPage();
        List<InterviewAnswer> list = interviewAnswerService.selectInterviewAnswerList(interviewAnswer);
        return getDataTable(list);
    }

    /**
     * 导出面试回答列表
     */
    @PreAuthorize("@ss.hasPermi('interview:answer:export')")
    @Log(title = "面试回答", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InterviewAnswer interviewAnswer)
    {
        List<InterviewAnswer> list = interviewAnswerService.selectInterviewAnswerList(interviewAnswer);
        ExcelUtil<InterviewAnswer> util = new ExcelUtil<InterviewAnswer>(InterviewAnswer.class);
        util.exportExcel(response, list, "面试回答数据");
    }

    /**
     * 获取面试回答详细信息
     */
    @PreAuthorize("@ss.hasPermi('interview:answer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(interviewAnswerService.selectInterviewAnswerById(id));
    }

    /**
     * 新增面试回答
     */
    @PreAuthorize("@ss.hasPermi('interview:answer:add')")
    @Log(title = "面试回答", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InterviewAnswer interviewAnswer)
    {
        return toAjax(interviewAnswerService.insertInterviewAnswer(interviewAnswer));
    }

    /**
     * 修改面试回答
     */
    @PreAuthorize("@ss.hasPermi('interview:answer:edit')")
    @Log(title = "面试回答", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InterviewAnswer interviewAnswer)
    {
        return toAjax(interviewAnswerService.updateInterviewAnswer(interviewAnswer));
    }

    /**
     * 删除面试回答
     */
    @PreAuthorize("@ss.hasPermi('interview:answer:remove')")
    @Log(title = "面试回答", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(interviewAnswerService.deleteInterviewAnswerByIds(ids));
    }

    /**
     * 提交面试录音
     * @param file 上传的文件
     * @param questionId 录音文件对应的问题
     * @return
     */
    @PostMapping("/handleAnswer")
    public AjaxResult handleAnswer(MultipartFile file,Long questionId) throws IOException {
        // 1、接收上传的文件
        // 文件名 answer_{questionId}.扩展名
        // 文件名的处理
        // 上传到七牛云，获取七牛云返回的文件数据
       QiNiuUtils.upload(file.getInputStream(),file.getOriginalFilename());

        // 把信息存储到mysql中
        InterviewAnswer answer = new InterviewAnswer();
        answer.setQuestionId(questionId);
        final String fileUrl = Constants.QINIU_URL_PREFIX + file.getOriginalFilename();
        answer.setAudioUrl(fileUrl);
        interviewAnswerService.insertInterviewAnswer(answer);
        // 获取answer的数据库的id
        final Long answerId = answer.getId();

        // 异步的形式

        new Thread(()-> {
            String jobId = HuaWeiSISUtils.doSubmit(fileUrl);
            Map<String, Object> map = HuaWeiSISUtils.getResult(jobId);

            // 修改这个answer的content和duration
            InterviewAnswer interviewAnswer = interviewAnswerService.selectInterviewAnswerById(answerId);
            Integer audioDuration = (Integer) map.get("audioDuration");
            interviewAnswer.setDuration(audioDuration.longValue());
            interviewAnswer.setContent((String) map.get("text"));
            interviewAnswerService.updateInterviewAnswer(interviewAnswer);

        }).start();

        return AjaxResult.success();
    }

    /**
     * 测试微信小程序录音单文件上传
     * @param file
     * @param questionId
     * @return
     * @throws IOException
     */
    @PostMapping("/testUploadRecord")
    public AjaxResult testUploadRecord(MultipartFile file,Long questionId) throws IOException {

        String filename =  file.getOriginalFilename();
        File target = new File("E:/IdeaProjects/RuoYi-Vue-master/RuoYi-Vue-master/files/" + filename);
        OutputStream outputStream = new FileOutputStream(target);
        InputStream inputStream = file.getInputStream();

        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }

        outputStream.flush();
        outputStream.close();

        return AjaxResult.success();
    }
}
